<template>
    <el-dialog v-model="visible" title="管理我的帖子" width="600px" @close="handleClose">
      <el-form v-if="editablePost" :model="editablePost" ref="formRef" label-position="top">
        <el-form-item label="帖子标题" prop="title">
          <el-input v-model="editablePost.title" placeholder="请输入帖子标题" />
        </el-form-item>
        <el-form-item label="帖子内容" prop="content">
          <el-input v-model="editablePost.content" type="textarea" :rows="8" placeholder="请输入帖子内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="handleDelete" :loading="isSubmitting">删除帖子</el-button>
          <div class="flex-grow"></div>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleUpdate" :loading="isSubmitting">保存修改</el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { ref, watch, reactive } from 'vue';
  import { useForumStore } from '@/stores/forum.js';
  import { ElMessage ,ElMessageBox } from 'element-plus';
  
  const props = defineProps({
    modelValue: Boolean,
    post: {
      type: Object,
      default: null
    }
  });
  const emit = defineEmits(['update:modelValue', 'post-updated', 'post-deleted']);
  
  const forumStore = useForumStore();
  const isSubmitting = ref(false);
  
  const editablePost = reactive({
    id: null,
    title: '',
    content: ''
  });
  
  const visible = ref(props.modelValue);
  watch(() => props.modelValue, (val) => {
    visible.value = val;
    if (val && props.post) {
      // 当弹窗打开时，用传入的帖子数据填充表单
      Object.assign(editablePost, {
          id: props.post.id,
          title: props.post.title,
          content: props.post.content
      });
    }
  });
  watch(visible, (val) => { emit('update:modelValue', val) });
  
  const handleClose = () => {
    visible.value = false;
  };
  
  const handleUpdate = () => {
    isSubmitting.value = true;
    forumStore.updatePost(
      editablePost.id,
      { title: editablePost.title, content: editablePost.content ,sectionId:1},
      () => {
        isSubmitting.value = false;
        emit('post-updated');
        handleClose();
      }
    );
  };
  
  const handleDelete = () => {
    isSubmitting.value = true;
    forumStore.deletePost(
      editablePost.id,
      () => {
        isSubmitting.value = false;
        emit('post-deleted');
        handleClose();
      }
    );
  };
  </script>
  
  <style scoped>
  .dialog-footer {
    display: flex;
    justify-content: space-between;
    width: 100%;
  }
  .flex-grow {
    flex-grow: 1;
  }
  </style>